'use strict';
import {
    View,
    Image,
    Text,
    Animated,
    TouchableHighlight,
    AsyncStorage,
    StyleSheet,
    LinkingIOS,
    AlertIOS,
    PushNotificationIOS,
    TouchableWithoutFeedback,
    ActivityIndicator
} from 'react-native';
import React from 'react';
import URL from '../config/server';
import {Utils} from '../config/utils';
import {Key} from '../config/key';

export default class Adv extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            bounceValue: new Animated.ValueXY({x: 0, y: -700}),
            jump: 4,
            delay: 4000,
            indicatorShow: false,
            imageSrc: 'temp',
            retain: 5,
            advLink: 'http://www.jrztb.net'
        };
    }

    componentDidMount() {
        this.fetchData();
        // Utils.versionCheck = true;
        // PushNotificationIOS.requestPermissions();
        // PushNotificationIOS.addEventListener('register', function(devicetoken){
        //     console.log('收到了注册信息');
        //     let TOKEN = 'http://101.200.229.204/smzt/app/token?token='+devicetoken;
        //     console.log(TOKEN);
        //     Utils.get(TOKEN, function (data) {
        //         console.log(data);
        //     })
        // });
        // PushNotificationIOS.addEventListener('notification', this._onNotification);
    }

    _onNotification(notification) {
        let that = this;
        AlertIOS.alert(
            '您收到一条新消息',
            '消息内容: ' + notification.getMessage(),
            [{
                text: '好的',
                onPress: ()=> {
                    console.log(notification.getMessage())
                }
            }]
        );
        PushNotificationIOS.setApplicationIconBadgeNumber(0);
    }


    fetchData() {
        let that = this;
        Utils.get(URL.local + 'adv/login', function (data) {
            console.log(data)
            if (data) {
                that.setState({
                    imageSrc: data.image,
                    advLink: data.url,
                    delay: data.second * 1000,
                    retain: data.second
                });
                that._AdvisUnmounted = false;
                Animated.spring(                          // Base: spring, decay, timing
                    that.state.bounceValue,                 // Animate `bounceValue`
                    {
                        toValue: {
                            x: 0,
                            y: 0
                        },
                        tension: 10                        // Animate to smaller size
                        // friction: 3,                          // Bouncier spring
                    }
                ).start();
                that.clock = setInterval(()=> {
                    that.setState({
                        retain: that.state.retain - 1
                    });
                    if (that.state.retain == 1) {
                        clearInterval(that.clock);
                        that._onJump();
                    }
                }, 1000);
                //定时器进行跳转
            }
        })
    }

    componentWillUnmount() {
        //clearTimeout(this.timer);
        clearInterval(this.clock);
        this._AdvisUnmounted = true;
    }

    _indicator() {
        if (this.state.indicatorShow) {
            return (
                <View style={styles.indicator}>
                    <Text style={styles.indicatorText}>加载中...</Text>
                    <ActivityIndicator
                        style={{alignSelf:'center',justifyContent:'center'}}
                        animating={true}
                        color={'#ffffff'}
                        size={'large'}/>
                </View>
            )
        } else {
            return <View></View>
        }
    }

    _onJump() {
        clearInterval(this.clock);
        var navigator = this.props.navigator;
        var that = this;
        this.setState({
            indicatorShow: true
        });
        //读取本地用户信息
        AsyncStorage.multiGet(['username', 'password'], cb);
        function cb(err, value) {
            if (!err && value) {
                var userName = value[0][1];
                var userPwd = value[1][1];
                navigator.replace({
                    id: 'LoginPage',
                    name: 'LoginPage',
                    message: {
                        regPhone:userName,
                        regPwd:userPwd
                    }
                })

            }
        }
    }

    render() {
        return (
            <View style={styles.container}>
                <View style={styles.content}>
                    <TouchableWithoutFeedback onPress={()=>{LinkingIOS.openURL(this.state.advLink);console.log(this)}}>
                        <Animated.Image
                            style={[styles.adv,{transform: this.state.bounceValue.getTranslateTransform()}]}
                            source={{uri: this.state.imageSrc}}
                        />
                    </TouchableWithoutFeedback>
                    <TouchableHighlight style={styles.timer} onPress={this._onJump.bind(this)} underlayColor='#ffffff'>
                        <View>
                            <Text style={styles.jumpText}>点击跳过{this.state.retain}s</Text>
                        </View>
                    </TouchableHighlight>
                </View>
                <View style={styles.footer}>
                    <Image
                        style={styles.logo}
                        source={require('../image/bottom.png')}
                    />
                </View>
                {this._indicator()}
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container:{
        flex: 1,
        backgroundColor: '#ffffff'
    },
    text:{
        color: 'white',
        fontSize: 32
    },
    content:{
        flex:12,
        alignItems: 'center',
        justifyContent: 'center'
    },
    adv:{
        width:Utils.size.width,
        height:400,
        resizeMode: Image.resizeMode.strech,
        flex:1
    },
    logo:{
        resizeMode: Image.resizeMode.contain,
        height:70
    },
    timer:{
        position:'absolute',
        backgroundColor: '#ffffff',
        top:25,
        right:10,
        borderColor:'#dddddd',
        borderWidth:1,
        borderRadius:2,
        padding:5
    },
    indicator:{
        position:'absolute',
        top:Utils.size.height/2-50,
        left:Utils.size.width/2-80,
        height:100,
        width:160,
        backgroundColor:'rgba(52,52,52,0.7)',
        alignItems:'center',
        justifyContent:'center',
        borderRadius:5
    },
    indicatorText:{
        fontSize:18,
        color:'#ffffff',
        textAlign:'center'
    },
    jumpText:{
        fontSize:11,
        color:'#de2920',
        fontWeight:'600'
    },
    footer:{
        flex:2,
        backgroundColor:'#ffffff',
        alignItems: 'center',
        justifyContent: 'center'
    }
})